package com.hd.springbootstudy.controller;

import com.hd.springbootstudy.entity.RespBean;
import com.hd.springbootstudy.entity.User;
import com.hd.springbootstudy.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Lemon
 * @Date: 2021/4/20 21:48
 *用户控制器
 */

/**
 * @RestController=@Controller+@ResponseBody
 */
@RestController
/**
 * Swagger扫描接口注解
 */
@Api(tags = "用户接口",value = "UserController")
public class UserController {
    /**
     * 日志 打印信息
     */
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    protected IUserService iUserService;
    /**
     * Get请求注解
     * @return String
     */
    @GetMapping("/")
    public String index(){
        return "hello world";
    }
    /**
     * Post请求注解
     */
    @PostMapping("/insertUser")
    /**
     * Swagger接口文档属性配置注解
     */
    @ApiOperation(value = "用户增加", notes = "用户名和密码不能为空", httpMethod = "POST")
    /**
     * 参数组
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userName",
                    value = "用户姓名", required = true, dataType = "String")
    })
    public RespBean insertUser(@Valid User user,  BindingResult bindingResult){
        /**
         * 将@Valid鉴权的错误信息返给前端
         */
        if (bindingResult.hasErrors()){
            Map<String, Object> map = new HashMap<>();
            List<FieldError> errors = bindingResult.getFieldErrors();
            logger.error("更新失败！");
            for (FieldError error : errors) {
                logger.error("错误的字段名：" + error.getField());
                logger.error("错误信息：" + error.getDefaultMessage());
                map.put(error.getField(), error.getDefaultMessage());
            }
            return RespBean.error(map);
        }
        iUserService.insertUser(user);
        return RespBean.ok("成功");
    }
}
